package com.duck.user.controller;


import com.duck.common.domain.Result;
import com.duck.user.utils.RedisUtils;
import com.duck.common.utils.UserContext;
import com.duck.user.domain.dto.ChangePasswordDto;
import com.duck.user.service.UserService;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Objects;

@RequestMapping("/user")
@RestController
public class ChangePasswordController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 登录后忘记密码
     * @param user 前端入参
     * @return 状态码
     */
    @PostMapping("/loginChangePassword/")
    public Result alterPassword( @NotNull @RequestBody ChangePasswordDto user){
        //获取用户ID
        String userId = String.valueOf(UserContext.getUser());
        if (Objects.isNull(userId)) {
            return new Result(404,"账号不存在");
        }
        if (!user.getNewPassword().equals(user.getConfirmPassword())) {
            return new Result(404, "两次密码输入不一致");
        }
        //从redis中取出邮箱的对应验证码
        String verifyCode = redisUtils.getValue(user.getEmail());
        if (!user.getCode().equals(verifyCode)) {
            return new Result(404, "验证码输入错误或验证码已过期");
        }
        if (user.getCode().isEmpty()) {
            return new Result(404, "请输入验证码");
        }
        //替换密码，把新密码加密
        HashMap<String, Object> insertData = new HashMap<>() {{
            put("email", user.getEmail());
            put("newPassword", BCrypt.hashpw(user.getNewPassword(), BCrypt.gensalt()));
        }};
        userService.changePassword(insertData);
        return new Result(200,"修改成功");
    }
}
